<script setup>
import dayjs from 'dayjs';
import { format } from 'date-fns'

definePageMeta({
	layout: 'flat'
})

useHead({
	title: 'HLS: Предварительное закрытие ортодонтических нарядов',
})

const mpp = useCookie('mpp');
const urlHome = useUrl();
const pend = ref(false);
const isOpen = ref(false);
const podrSelect = ref(0);
const q = ref('');
const p = ref('');
const d = ref('');
const dateSelect = ref(new Date());
const modalHead = ref({});
const selectedTech = ref(0);
const selectedPol = ref(0);
const selectedLit = ref(0);
const selectedCadcam = ref(0);
const uslugi = ref([]);

const { data: specList } = await useFetch(`${urlHome.value}lab/list_all_prof/`)

const { data: narList, execute: narFetch } = await useFetch(`${urlHome.value}lab/nar_ortodont_open/`, {
	query: {
		mpp: mpp.value,
		podr: podrSelect,
	}
})

const filteredRows = computed(() => narList.value.filter(naryad =>
	String(naryad.nkv).toLowerCase().includes(q.value.toLowerCase()) &&
	String(naryad.patient_name).toLowerCase().includes(p.value.toLowerCase()) &&
	String(naryad.naryad_doc__user__fam).toLowerCase().includes(d.value.toLowerCase())
))

function resetSearch() {
	q.value = '';
	p.value = '';
	d.value = '';
}

const podrList = [{ "lpu_name": "Все подразделения", "lpu_number": 0 }, { "lpu_name": "Поликлиника №3", "lpu_number": 165 }, { "lpu_name": "Березовское стоматологическое отделение", "lpu_number": 3 }, { "lpu_name": "Яшкинское стоматологическое отделение", "lpu_number": 32 }, { "lpu_name": "Поликлиника №5", "lpu_number": 245 }, { "lpu_name": "Стоматологическое отделение", "lpu_number": 243 }, { "lpu_name": "Поликлиника №4", "lpu_number": 236 }, { "lpu_name": "Поликлиника №2", "lpu_number": 164 }, { "lpu_name": "Поликлиинка №1", "lpu_number": 162 }, { "lpu_name": "Топкинское стоматологическое отделение", "lpu_number": 28 }]

const columns = [
	{ key: 'nkv', label: 'Наряд' },
	{ key: 'patient_name', label: 'Пациент' },
	{ key: 'dou', label: 'Дата' },
	{ key: 'naryad_doc__user__fam', label: 'Врач' },
	{ key: 'lpu__name_lpu', label: 'Поликлиника' },
	{ key: 'opl__name_opl', label: 'Оплата' },
	{ key: 'actions' }
]

const columnsUsl = [{
	key: 'kusl',
	label: 'Код'
}, {
	key: 'nusl',
	label: 'Название услуги'
}, {
	key: 'kol',
	label: 'Кол-во'
}, {
	key: 'uet',
	label: 'УЕТ'
}, {
	key: 'price',
	label: 'Цена'
}, {
	key: 'stu',
	label: 'Сумма'
}, {
	key: 'actions'
}]


async function openModal(row) {
	const response = await $fetch(`${urlHome.value}lab/uslugi_by_nkv/`, {
		query: {
			naryad_nkv: row.nkv,
		}
	})
	if (response) {
		uslugi.value = response
	}
	modalHead.value = row
	console.log(row)
	console.log(typeof (row.sdl_set__tech), row.sdl_set__tech);
	selectedTech.value = row.sdl_set__tech;
	selectedPol.value = row.sdl_set__pol;
	selectedLit.value = row.sdl_set__lit;
	selectedCadcam.value = row.sdl_set__cadcam;
	isOpen.value = true
}

async function closeNarByDoc(naryad_id) {
	console.log("closeNarByDoc")
	const response = await $fetch(`${urlHome.value}lab/close_ortodont_by_st/`, {
		query: {
			naryad_id: naryad_id,
			date_close: dayjs(dateSelect.value).format("YYYY-MM-DD"),
		}
	})

	if (response.ok) {
		console.log(response.status);
		narFetch()
		isOpen.value = false
	}
}

async function changeSpec(naryad_id) {
	let formData = new FormData();
	formData.append('tech', selectedTech.value)
	formData.append('lit', selectedLit.value)
	formData.append('pol', selectedPol.value)
	formData.append('cadcam', selectedCadcam.value)
	formData.append('naryad_id', naryad_id)

	const response = await $fetch(`${urlHome.value}lab/sdl_set_update/`, {
		method: 'POST',
		body: formData
	})
	if (response.ok) {
		await closeNarByDoc(naryad_id)
	} else {
		alert("error")
	}
}

// watch(date, (newValue, oldValue) => {
// 	console.log(newValue, oldValue)
// })

</script>
<style></style>

<template>
	<div>
		<div class="flex flex-row gap-2">
			<USelect v-model.number="podrSelect" :options="podrList" option-attribute="lpu_name"
				value-attribute="lpu_number" color="green" />
			<UButton :disabled="pend" label="Загрузить" @click="narFetch" />
		</div>
		<div class="flex px-3 py-3.5 border-b border-gray-200 dark:border-gray-700 gap-2">
			<UInput v-model="q" placeholder="Наряд №..." />
			<UInput v-model="p" placeholder="Пациент..." />
			<UInput v-model="d" placeholder="Врач..." />
			<UButton @click="resetSearch" label="Очистить" />
		</div>
		<UTable :columns="columns" :rows="filteredRows" :config="{
			tr: {
				active: 'hover:green-950 dark:green-950/50'
			}
		}">
			<template #dou-data="{ row }">
				<span>{{ dayjs(row.dou).format('DD.MM.YYYY') }}</span>
			</template>
			<template #actions-data="{ row }">
				<UButton color="gray" @click="openModal(row)" icon="i-heroicons-document-magnifying-glass" />
			</template>
		</UTable>
		<ClientOnly>
			<UModal v-model="isOpen" :ui="{ base: 'max-w-6xl', width: '' }">
				<UCard :ui="{
					base: 'h-full flex flex-col',
					rounded: '',
					divide: 'divide-y divide-gray-100 dark:divide-gray-800',
					body: {
						base: 'grow'
					}
				}">
					<template #header>
						<div class="flex items-center justify-between">
							<h3 class="text-base font-semibold leading-6 text-gray-900 dark:text-white">
								Наряд № {{ modalHead.nkv }}
							</h3>
							<UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1"
								@click="isOpen = false" />
						</div>
						<div class="grid grid-cols-3 grid-rows-2 gap-4 py-10">
							<div>Номер наряда: <b>{{ modalHead.nkv }}</b></div>
							<div>Дата оформления: <b>{{ dayjs(modalHead.dou).format('DD.MM.YYYY') }}</b></div>
							<div>Вид оплаты: <b>{{ modalHead.opl__name_opl }}</b></div>
							<div>Врач: <b>{{ `${modalHead.naryad_doc__user__fam} ${modalHead.naryad_doc__user__im[0]}.
									${modalHead.naryad_doc__user__im[0]}` }}</b></div>
							<div>ФИО Пациента: <b>{{ modalHead.patient_name }}</b></div>
							<div>Дата рождения: <b>{{ dayjs(modalHead.patient__dr).format('DD.MM.YYYY') }}</b></div>
						</div>
						<UDivider />
						<div class="flex flex-row pt-10 text-center">
							<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
								<label class="label">
									<span class="label-text ">Техник</span>
								</label>
								<USelect v-model="selectedTech" color="primary" variant="outline"
									:options="specList.list_tech" option-attribute="name" value-attribute="mpp">
								</USelect>
							</div>
							<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
								<label class="label">
									<span class="label-text">Полировщик</span>
								</label>
								<USelect v-model="selectedPol" color="primary" variant="outline"
									:options="specList.list_pol" option-attribute="name" value-attribute="mpp" />
							</div>

							<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
								<label class="label">
									<span class="label-text">Литейщик</span>
								</label>
								<USelect v-model="selectedLit" color="primary" variant="outline"
									:options="specList.list_lit" option-attribute="name" value-attribute="mpp" />
							</div>

							<div class="form-control w-full md:max-w-xs lg:max-w-sm xs:max-w-lg">
								<label class="label">
									<span class="label-text">CAD/CAM</span>
								</label>
								<USelect ref="col" v-model="selectedCadcam" color="primary" variant="outline"
									:options="specList.list_cadcam" option-attribute="name" value-attribute="mpp" />
							</div>
						</div>
						<div class="flex flex-row-reverse gap-2 pt-4">
							<div>
								<UButton label="Сохранить" @click="changeSpec(modalHead.id)" />
							</div>
							<div>
								<UPopover :popper="{ placement: 'bottom-start' }">
									<UButton variant="outline" icon="i-heroicons-calendar-days-20-solid"
										:label="format(dateSelect, 'd.MM.yyy')" />

									<template #panel="{ close }">
										<VDatePicker v-model="dateSelect" @update:model-value="close" />
									</template>
								</UPopover>
							</div>
							<div class="font-bold">Дата закрытия: </div>
						</div>
					</template>
					<div>
						<UTable :rows="uslugi" :columns="columnsUsl">
							<template #kusl-data="{ row }">
								<span>{{ row.kusl }}</span>
							</template>
							<!-- <template #actions-data="{ row }">
							<UButton color="gray" @click="delUsl(row.id)" icon="i-heroicons-trash-20-solid" />
						</template> -->
						</UTable>
					</div>
				</UCard>
			</UModal>
		</ClientOnly>
	</div>
</template>